﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Xrm.Framework.Test.Integration;
using Xrm.Solutions.FrameworkSample.Common.Entities;


namespace Xrm.Solutions.FrameworkSample.XrmIntegrationTests.Plugins
{
    /// <summary>
    /// Verify an Identity check has been created after its corresponding contact creation
    /// </summary>
    [TestClass]
    public class TestPostContactCreate : PluginIntegrationTest
    {
        #region Instance Variables

        private Contact contact;

        private xdft_identitycheck identityCheck;

        #endregion

        #region Setup

        protected override OrganizationRequest SetupTriggerRequest()
        {
            contact = new Contact();
            contact.FirstName = "James";
            contact.LastName = "Bond";
            contact.BirthDate = DateTime.Now;

            CreateRequest request = new CreateRequest();
            request.Target = contact;
            return request;
        }

        #endregion

        #region Test

        [TestMethod]
        public void RunTestPostContactCreate()
        {
            base.Test();
        }

        #endregion

        #region Verify

        protected override void Verify()
        {
            Assert.IsNull(Error);

            CreateResponse response = this.TriggerResponse as CreateResponse;
            contact.Id = response.id;

            using (XrmServiceContext context = new XrmServiceContext(this.OrganizationService))
            {
                var identityChecks = from ic in context.xdft_identitycheckSet
                                     where ic.xdft_ContactId.Id == contact.Id
                                     select ic;

                Assert.IsTrue(identityChecks.ToList().Count() == 1);

                identityCheck = identityChecks.First();
                Assert.AreEqual(identityCheck.xdft_FirstName, contact.FirstName);
                Assert.AreEqual(identityCheck.xdft_LastName, contact.LastName);
                Assert.IsTrue(identityCheck.xdft_DateOfBirth.HasValue);
                Assert.AreEqual(identityCheck.xdft_DateOfBirth.Value.Date, contact.BirthDate.Value.Date);
            }
        }

        #endregion

        #region Clean Up

        protected override void CleanUp()
        {
            base.CleanUp();
            this.OrganizationService.Delete(identityCheck.LogicalName, identityCheck.Id);
            this.OrganizationService.Delete(contact.LogicalName, contact.Id);
        }

        #endregion
    }
}
